const config = require("../config/config");
const tokenOld = require("../config/token.json");
const request = require("superagent");
const path = require("path");

const {
  promisify
} = require("util");
const fs = require("fs");
const writeFile = promisify(fs.writeFile);

class CreateToken {
  constructor() {}
  async updateToken() {
    let date = new Date();
    let updateAt = date.getTime();
    if (updateAt - tokenOld.updateAt < 7200) {
      return tokenOld
    }
    try {
      let rev = await request.get(config.access_token_url);
      let res = JSON.parse(rev.text);
      if (res.errcode == 0) {
        let token = {
          errcode:0,
          errmsg:'',
          access_token: res.access_token,
          updateAt
        };
        console.log(`the dirname is :${__dirname}`);
        await writeFile(path.resolve(__dirname, '../config/token.json'), JSON.stringify(token))
        return token
      }
    } catch (err) {
      return {
        errcode: -1,
        errmsg: "获取access_token失败！",
        access_token:'',
        updateAt
      };
    }
  }
}
module.exports = {
  CreateToken
};